import {
  Controller,
  Body,
  Post,
  Get,
  Query,
  Put,
  Param,
  Delete,
} from '@nestjs/common'
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger'
import { RoleModel, RoleClass, bulkQueryDto } from './role.model'
import type { IResposeBase } from '../common/response'
@ApiTags('角色管理')
@ApiBearerAuth()
@Controller('admin/acl/role')
export class RoleController {
  @Get('/paginate')
  @ApiOperation({
    summary: '获取分页角色列表',
  })
  async getPaginatedUsers(
    @Query('page') page = 1,
    @Query('limit') limit = 10,
    @Query('keyword') keyword = '',
  ) {
    const users = await RoleModel.find<RoleClass>({
      name: { $regex: keyword, $options: 'i' },
    })
      .select('-__v')
      .sort({ _id: -1 })
      .skip((Number(page) - 1) * Number(limit))
      .limit(Number(limit))
      .exec()

    const total = await RoleModel.countDocuments({
      name: { $regex: keyword, $options: 'i' },
    })

    return {
      data: users,
      meta: {
        currentPage: Number(page),
        itemPerPage: Number(limit),
        totalItems: total,
        totalPages: Math.ceil(total / Number(limit)),
      },
    }
  }

  @Post('/many')
  @ApiOperation({ summary: '根据mongodb的_id获取集合' })
  async findMary(@Body() body: bulkQueryDto) {
    return await RoleModel.find<RoleClass>({
      _id: { $in: body },
    }).exec()
  }

  @Post()
  async create(@Body() createRoleDto: RoleClass): Promise<IResposeBase> {
    await RoleModel.create(createRoleDto)
    return {
      success: true,
      message: '角色创建成功！',
    }
  }

  @Put(':id')
  @ApiOperation({ summary: '更新用户' })
  async updateUser(
    @Param('id') id: string,
    @Body() UpDateData: RoleClass,
  ): Promise<IResposeBase> {
    await RoleModel.findByIdAndUpdate(id, UpDateData, {
      runValidators: true,
      new: true, //提供应用更新后的对象
    }).exec()
    return {
      success: true,
      message: '角色更新成功！',
    }
  }

  @Delete(':id')
  @ApiOperation({ summary: '删除角色' })
  async deleteUser(@Param('id') id: string): Promise<IResposeBase> {
    await RoleModel.findByIdAndDelete(id).exec()
    return {
      success: true,
      message: '删除角色成功！',
    }
  }
}
